--
-- Author: mm
-- Date: 2018-03-19 14:55:37
--
-- NewguildModel
--

local BoxItemVo = require("app.reward.models.BoxItemVo")

local NewguildInfo = import(".NewguildInfo") -- 公会基础数据结构
local guildApplicantVo = import(".guildApplicantVo") -- 申请者数据结构
local guildMemberVo = import(".guildMemberVo") -- 成员数据结构
local challengeVo = import(".challengeVo") -- 公会挑战数据结构
local guildTalentVo = import(".guildTalentVo")--公会天赋数据结构

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ModelBase)
local table_insert = table.insert

local baseIconColorList = {
	cc.c3b( 21, 98, 204 ),cc.c3b( 31, 158, 205 ),cc.c3b( 36, 218, 212 ),cc.c3b( 24, 199, 28 ),cc.c3b( 137, 240, 96 ),
	cc.c3b( 241, 235, 84 ),cc.c3b( 239, 190, 39 ),cc.c3b( 231, 125, 27 ),cc.c3b( 218, 42, 29 ),cc.c3b( 215, 62, 116 ),
	cc.c3b( 213, 89, 194 ),cc.c3b( 171, 81, 213 ),cc.c3b( 132, 65, 208 ),cc.c3b( 92, 65, 208 ),cc.c3b( 58, 61, 174 )
}
local additionalIconColorList = {
	cc.c3b( 21, 98, 204 ),cc.c3b( 31, 158, 205 ),cc.c3b( 36, 218, 212 ),cc.c3b( 24, 199, 28 ),cc.c3b( 137, 240, 96 ),
	cc.c3b( 241, 235, 84 ),cc.c3b( 239, 190, 39 ),cc.c3b( 231, 125, 27 ),cc.c3b( 218, 42, 29 ),cc.c3b( 215, 62, 116 ),
	cc.c3b( 213, 89, 194 ),cc.c3b( 171, 81, 213 ),cc.c3b( 132, 65, 208 ),cc.c3b( 92, 65, 208 ),cc.c3b( 58, 61, 174 )
}

function ClassRef:ctor(data)
    self.super.ctor(self, data)
end

function ClassRef:init()
	self._myGuildInfo = nil -- 我的公会信息
	self._myGuildMemberInfo = nil -- 我作为成员的信息
	self._myGuildMemberList = {} -- 我的公会成员信息
	self._haveChallengeBoxGet = false --是否有挑战宝箱领取
	self._curPageGuildInfoList = {}
	self._curGuildListStartIdx = 0 -- 当前公会查询列表开始索引
	self._curGuildListEndIdx = 0 --当前公会查询列表结束的索引
	self._applyTips = false -- 是否有新申请者
	self._guildTalents = {} --公会天赋数据
	self:_initGuildTalents()
end

--申请界面数据清空
function ClassRef:clearPreCreateData()
	self._curPageGuildInfoList = {}
	self._curGuildListStartIdx = 0 -- 当前公会查询列表开始索引
	self._curGuildListEndIdx = 0 --当前公会查询列表结束的索引
end

--初始化公会天赋数据
function ClassRef:_initGuildTalents()
	local guildTalentConfig = GD:queryGuildTalents()
	
	for k,v in ipairs(guildTalentConfig) do
		local gTalentInfo = guildTalentVo.new(v)
		self._guildTalents[k] = gTalentInfo
	end
end

--获取公会的天赋数据
function ClassRef:getGuildTalents()
	return self._guildTalents
end

--收到更新消息的时候更新公会天赋数据
function ClassRef:_updateGuildTalents(myGuildInfo)
	local myGuildTalentInfos = myGuildInfo:getGuildCurTalentInfo()
	--dump(myGuildTalentInfos," ------------------->>>>> _updateGuildTalents ")
	for _,v in ipairs(self._guildTalents) do
		v:updateDataByServer(myGuildTalentInfos)
	end
end

-- 成员排序
-- 自身角色排第一，
-- 第一优先级为在线，在线的排上面；
-- 第二优先级为身份，根据会长→精英→普通的顺序由高到低排列；
-- 第三优先级为贡献值，根据贡献值由高到低排列；
-- 第四优先级为入会时间，根据入会的早→晚由高到低排列。
function ClassRef:_sortMemberList()
	table.sort( self._myGuildMemberList, function ( a, b )
		if a:isMe() then
			return true
		elseif b:isMe() then
			return false
		else
			if a:isOnline() and not b:isOnline() then -- a在线，B不在线
				return true
			elseif not a:isOnline() and b:isOnline() then -- a不在线，B在线
				return false

			-- 都在线 || 都不在线
			elseif a:getPosition() == b:getPosition() then --地位相同
				--优先爵位
				if a:getTitleId() == b:getTitleId() then
					if a:getDonateLv() == b:getDonateLv() then --捐献等级相同
						if a:getDonateCopies() == b:getDonateCopies() then -- 捐献份数
							if a:getJoinedTimes() == b:getJoinedTimes() then -- 入会时间相同
								return a:getMemberId() < b:getMemberId()
							else
								return a:getJoinedTimes() < b:getJoinedTimes()
							end
						else
							return a:getDonateCopies() > b:getDonateCopies()
						end
					else
						return a:getDonateLv() > b:getDonateLv()
					end
				else
					return a:getTitleId() > b:getTitleId()
				end
			else
				return a:getPosition() < b:getPosition()
			end
		end
	end )
end
-- 返回基础图标颜色值列表
function ClassRef:getBaseIconColorList()
	return baseIconColorList
end
-- 返回附加图标颜色值列表
function ClassRef:getAdditionalIconColorList()
	return additionalIconColorList
end

function ClassRef:getMyGuildMemberInfo()
	return self._myGuildMemberInfo
end

--公会当前激活的最大爵位
function ClassRef:getMaxActiveTerritoryId()
	return self._myGuildInfo:getMaxActiveTerritoryId()
end

-- guildInfo 结构
function ClassRef:setMyGuildMemberInfo( guildMemberInfo )
	-- dump( guildMemberInfo, " ------------------->>>>> setMyGuildMemberInfo " )
	if guildMemberInfo and next( guildMemberInfo ) then -- 有数据？

		if self._myGuildMemberInfo then
			self._myGuildMemberInfo:read(guildMemberInfo)
		else
			self._myGuildMemberInfo = guildMemberVo.new( guildMemberInfo )
		end
	else
		self:clearMyGuildInfo()
	end
end


function ClassRef:getMyGuildInfo()
	return self._myGuildInfo
end
-- guildInfo 结构
function ClassRef:setMyGuildInfo( guildInfo )
	--dump( guildInfo, " ------------------->>>>> setMyGuildInfo " )
	if next( guildInfo ) then -- 有数据？
		if self._myGuildInfo then
			--若出现公会名字变化 则发出提示 公会已改名

			if self._myGuildInfo:getGuildName() ~= guildInfo.name then
				app:sendMsg("IMModel", "addGuildMsg", string.format(L("rename7"), guildInfo.name))
			end
			self._myGuildInfo:read(guildInfo)
		else
			self._myGuildInfo = NewguildInfo.new( guildInfo )
			EM:notify( "GuildUpdate", guildInfo.gid )
		end

		self:_updateGuildTalents(self._myGuildInfo)
		self:updateMyGuildInfo()
	else
		self:clearMyGuildInfo()
	end
end

function ClassRef:updateMyGuildInfo()
	EM:notify("onMyGuildInfoUpdate", self._myGuildInfo)
end

function ClassRef:clearMyGuildInfo()
	self._myGuildInfo = nil
	self._myGuildMemberInfo = nil
	self._myGuildMemberList = {}
	self._guildTalents = {} --公会天赋数据重置
	self:_initGuildTalents()
	app:sendMsg( "NewguildPreController", "closeView" )
	app:sendMsg( "NewguildPreController", "closeCreateView" )
	app:sendMsg( "NewguildPreController", "closeCreateSureView" )
	app:sendMsg( "NewguildController", "closeView" )
	app:sendMsg( "NewguildController", "closeDonateView" )
end

function ClassRef:hasGuild()
	return self._myGuildInfo ~= nil
end
function ClassRef:getGuildId()
	if self._myGuildInfo then
		return self._myGuildInfo:getGuildId()
	end
	return 0
end

-- uid否是会长
function ClassRef:isGuildLeader( uid )
	local memberDataTemp = nil
	if uid then -- 指定了uid
		for i,v in ipairs( self._myGuildMemberList ) do
			if v:getMemberId() == uid then
				memberDataTemp = v
				break
			end
		end
	else -- 没指定uid，取自己作为成员时候的数据
		memberDataTemp = self:getMyGuildMemberInfo()
	end
	if memberDataTemp then
		return memberDataTemp:isGuildLeader()
	end
	return false
end

function ClassRef:getGuildLeader()
	local memberDataTemp = nil
	if not self._myGuildMemberList then
		return
	end
	for i,v in ipairs( self._myGuildMemberList ) do
		if v:isGuildLeader() then
			return v
		end
	end
end

function ClassRef:isGuildManager( uid )
	local memberDataTemp = nil
	if uid then -- 指定了uid
		for i,v in ipairs( self._myGuildMemberList ) do
			if v:getMemberId() == uid then
				memberDataTemp = v
				break
			end
		end
	else -- 没指定uid，取自己作为成员时候的数据
		memberDataTemp = self:getMyGuildMemberInfo()
	end
	if memberDataTemp then
		return memberDataTemp:isGuildManager()
	end
	return false
end

function ClassRef:judgePeerageIsGuildManager(maxActiveTerritoryId, titleId)
	local forceInfo = GD:queryPeerageById(maxActiveTerritoryId)
	--竖线分割
	if forceInfo and forceInfo.elitePeerage then
		local orderStrArr = string.split(forceInfo.elitePeerage, "|")
		for k, v in ipairs(orderStrArr) do
			if tonumber(v) == tonumber(titleId) then
				return true
			end
		end
	end
	return false
end

--公会是否是势力
function ClassRef:isForce()
	if self._myGuildInfo then
		return next(self._myGuildInfo:getOwnTownList())
	end
	return false
end

function ClassRef:getGuildName()
	if self._myGuildInfo then
		return self._myGuildInfo:getGuildName()
	end
	return L("noguild")
end

function ClassRef:getGuildMemberMaxNum()
	if self._myGuildInfo then
		return self._myGuildInfo:getGuildMaxMemberNum()
	end
	return -1
end

function ClassRef:getGuildMembers()
	return self._myGuildMemberList
end
function ClassRef:getGuildMemberByUid( uid )
	if uid then -- 指定了uid
		for i,v in ipairs( self._myGuildMemberList ) do
			if v:getMemberId() == uid then
				return v
			end
		end
	else -- 没指定uid，取自己作为成员时候的数据
		return self:getMyGuildMemberInfo()
	end
	return nil
end
-- 根据 str 过滤成员
function ClassRef:getGuildMembersByName( str, showOffline ) -- showOffline-是否显示离线成员
	local memberList = {}
	for i,v in ipairs( self._myGuildMemberList ) do
		if string.find( v:getMemberName(), str ) then
			if showOffline then
				table.insert( memberList, v )
			else
				if v:isOnline() then
					table.insert( memberList, v )
				end
			end
		end
	end
	return memberList
end

-- 是否可以继续扩充成员人数
function ClassRef:canContinueUpLimitNum()
	if self._myGuildInfo then
		local curMemberMaxNum = self._myGuildInfo:getGuildMaxMemberNum() -- 公会当前最大人数
		local guildLvConf = GD:queryGuildLvById( self._myGuildInfo:getGuildLv() )
		local curLvMaxNum = tonumber( guildLvConf.member ) + tonumber( guildLvConf.memberEx ) -- 公会当前等级可以达到的最大人数

		 -- 根据汝东所说：只有人数没达到当前等级人数上限就可以继续扩充。不再是没2级给一次扩充次数了。。
		return curMemberMaxNum < curLvMaxNum
	end
	return false
end

-- 返回新申请者状态
function ClassRef:getNewApplyTips()
	return self._applyTips
end

-- 返回是否有挑战宝箱的领取
function ClassRef:getHaveChallengeBoxGet()
	return self._haveChallengeBoxGet
end

-- 返回当前所处页数
function ClassRef:getCurGuildListStartIdx()
	return self._curGuildListStartIdx
end

function ClassRef:getCurGuildListEndIdx()
	return self._curGuildListEndIdx
end

------------------------------------------------ receive ------------------------------------------------
-- 我的公会信息更新
function ClassRef:onMyGuildInfoUpdate( ret )
	self:setMyGuildInfo( ret.myGuildInfo )
	self:setMyGuildMemberInfo( ret.myMemberInfo )
end

-- 更新公会其中一个成员的数据
function ClassRef:onGuildMemberUpdate( ret )
	-- dump( ret, " ------------------->>>>> onGuildMemberUpdate " )

	local uId = ret.memberInfo.userBaseInfo.uid --玩家唯一ID
	if ret.opt == "insert" then -- 新进成员
		local newMemberData = guildMemberVo.new( ret.memberInfo ) -- 待更新的成员数据
		local memberData = self:getGuildMemberByUid( newMemberData:getMemberId() ) -- 旧有的成员数据
		--assert( not memberData, " ----->>> onGuildMemberUpdate 新进成员，但是在成员列表中找到旧数据了？" )


		if not memberData then
			table.insert( self._myGuildMemberList, newMemberData )
			self:_sortMemberList()
		end

		if newMemberData:isMe() then -- 新进的是我
			app:sendMsg( "NewguildPreController", "closeView" )
			app:sendMsg( "NewguildPreController", "closeCreateView" )
			app:sendMsg( "NewguildPreController", "closeCreateSureView" )

			-- if not ( BattleManager:isBattle() or StoryManager:isEnterStoryMode() ) then -- 非剧情、非战斗中，才直接展开UI
			-- 	app:sendMsg( "NewguildController", "openView" )
			-- end
			UD:updateGuildNewPoint( true ) -- 显示红点
		end
		--显示谁加入了公会
		app:sendMsg("IMModel", "addGuildMsg", string.format(L("guildchat6"), newMemberData:getMemberName()))
	elseif ret.opt == "update" or ret.opt == "delete" then -- 成员数据更新 或者 成员退出、被踢
		local dataIdx = 0

		for i,v in ipairs( self._myGuildMemberList ) do
			if v:getMemberId() == uId then
				dataIdx = i
				break
			end
		end
		if 0 >= dataIdx then -- 在成员列表中找不到变化的数据？
			-- release_print( " ----->>> onGuildMemberUpdate update/delete 在成员列表中找不到数据？" )
			return
		end
		if ret.opt == "update" then
			--这里将出现职位变化 精英变化等等
			--先获取旧的职位和精英等
			local oldTitle = self._myGuildMemberList[ dataIdx ]:getTitleId()
			local oldPos = self._myGuildMemberList[ dataIdx ]:getPosition()
			self._myGuildMemberList[ dataIdx ]:read(ret.memberInfo)
			local newTitle = self._myGuildMemberList[ dataIdx ]:getTitleId()
			local newPos = self._myGuildMemberList[ dataIdx ]:getPosition()
			--优先判断职位变化
			if newTitle ~= oldTitle and oldPos ~= 1 then
				--若有职位变化 且不是会长 为了排除旧会长转让的消息
				if newTitle == 0  then
					--显示撤销官职
					app:sendMsg("IMModel", "addGuildMsg", string.format(L("guildchat2"), self._myGuildMemberList[ dataIdx ]:getMemberName()))
				else
					--显示授予官职
					local titleInfo = GD:queryPeerageById(newTitle)
					if titleInfo then
						if newPos == 1 then
							--如果我现在变成了会长
							app:sendMsg("IMModel", "addGuildMsg", string.format(L("guildchat5"), self._myGuildMemberList[ dataIdx ]:getMemberName()))
						else
							app:sendMsg("IMModel", "addGuildMsg", string.format(L("guildchat1"), self._myGuildMemberList[ dataIdx ]:getMemberName(), L(titleInfo.name)))
						end
					end
				end
			elseif newPos ~= oldPos and oldPos ~= 1 then
				--若有精英变化
				if newPos == 2 then
					--被授予精英
					app:sendMsg("IMModel", "addGuildMsg", string.format(L("guildchat3"), self._myGuildMemberList[ dataIdx ]:getMemberName()))
				elseif newPos == 3 then
					--被取消精英
					app:sendMsg("IMModel", "addGuildMsg", string.format(L("guildchat4"), self._myGuildMemberList[ dataIdx ]:getMemberName()))
				elseif newPos == 1 then
					--被转让会长
					app:sendMsg("IMModel", "addGuildMsg", string.format(L("guildchat5"), self._myGuildMemberList[ dataIdx ]:getMemberName()))
				end
			end
			--sort要放在最后
			self:_sortMemberList()
		elseif ret.opt == "delete" then
			--离开公会的玩家不会看到此消息
			if uId ~= UD.player.uid then
				app:sendMsg("IMModel", "addGuildMsg", string.format(L("guildchat7"), self._myGuildMemberList[ dataIdx ]:getMemberName()))
			end
			table.remove( self._myGuildMemberList, dataIdx )
		end
	end

	if uId == UD.player.uid then -- 如果变化数据是我
		if ret.opt == "delete" then -- 我的公会数据没有了：主动退出 或者 被踢了
			self:setMyGuildMemberInfo()
			app:sendMsg( "NewguildPreController", "closeView" )
			app:sendMsg( "NewguildPreController", "closeCreateView" )
			app:sendMsg( "NewguildPreController", "closeCreateSureView" )
			app:sendMsg( "NewguildController", "closeView" )
			app:sendMsg( "NewguildController", "closeDonateView" )
			EM:notify( "QuitGuild" )
		else
			self:setMyGuildMemberInfo( ret.memberInfo )
			if ret.opt == "insert" then
				EM:notify( "JoinGuild" )
			end
		end
	end

	app:sendMsg( "NewguildController", "refreshGuildMemberList")
	app:sendMsg( "NewguildController", "refreshManagePanelVisible")
end

-- 公会挑战信息更新
function ClassRef:onGuildChallengeInfoUpdate( challengeInfo )
	local guildChallengeList = {}
	self._haveChallengeBoxGet = false
	for i,v in ipairs( challengeInfo ) do
		local challengeInfo = challengeVo.new( v )
		guildChallengeList[ #guildChallengeList + 1 ] = challengeInfo
		if challengeInfo:isCompleted() and not challengeInfo:hadGotReward() then
			self._haveChallengeBoxGet = true
		end
	end

	table.sort( guildChallengeList, function(a, b)
		return a:getChallengeQuality() < b:getChallengeQuality()
	end )

	if next( guildChallengeList ) then
		app:sendMsg( "NewguildController", "refreshGuildChallengePanel", guildChallengeList )
	end

	UD:updateGuildNewPoint( self:_judgeNeedShowRedPoint() )
	app:sendMsg( "NewguildController", "refreshChallengeTips" )
end

-- 更新新申请者标记
function ClassRef:onGuildNewApplicant( applyTips )
	self._applyTips = applyTips
	app:sendMsg( "NewguildController", "refreshNewApplyTips" )
	UD:updateGuildNewPoint( self:_judgeNeedShowRedPoint() )
end


function ClassRef:_judgeNeedShowRedPoint()
--若有申请者 或者 挑战有宝箱可以领取
	if self._haveChallengeBoxGet or self._applyTips then
		return true
	else
		return false
	end
end

-- 公会经验值增加通知
function ClassRef:onGuildExpAdded( exp )
	app:sendMsg("IMModel", "addSystemMsg", L("lua_code_text_109"), exp)
end

-- 邀请入会，通知被邀请者
function ClassRef:onGuildInvitePlaneInfo(ret)
	-- 右下角的通知
	local params = {
		remindId = Constant.FUNC_TYPE_GUILD_INVITE,
		dataTemp = {name = ret.inviterBaseInfo.name, guildName = ret.guilName, guildId = ret.guildId}
	}
	local desktopController = UIHandler:getDesktopController()
	if desktopController then
		desktopController:insertFourthTips( params )
	end
end

------------------------------------------------ request ------------------------------------------------
-- 公会列表
function ClassRef:reqGuildList( startIdx )
	--dump("申请起始点 "..startIdx)
	app.session:request("pb_guild.C2S_GuildList", { startIndex = startIdx }, function(ret)
		self._curGuildListStartIdx = ret.startIndex

		self._curPageGuildInfoList = {}
		for i,v in ipairs( ret.guildInfos ) do
			local guildInfoTemp = NewguildInfo.new( v )
			table.insert( self._curPageGuildInfoList, guildInfoTemp )
		end
		self._curGuildListEndIdx = ret.startIndex + #self._curPageGuildInfoList - 1
		--print(self._curGuildListStartIdx,self._curGuildListEndIdx)
		app:sendMsg( "NewguildPreController", "refreshGuildList", self._curPageGuildInfoList)
	end)
end

-- 查询公会信息
function ClassRef:reqMyGuildInfo()
	app.session:request("pb_guild.C2S_MyGuildInfo", {}, function(ret)

	end)
end

-- 查询公会信息
-- 暂时没用上
-- function ClassRef:reqGuildInfo( gidTemp )
-- 	print( " ---------->>> reqGuildInfo " , gidTemp )
-- 	app.session:request("pb_guild.C2S_GuildInfo", { gid = gidTemp }, function(ret)
-- 		dump( ret, " ---------->>> reqGuildInfo ret" )
-- 		-- ret = S2C_GuildInfo 结构
-- 	end)
-- end

-- 搜索公会
function ClassRef:reqQueryGuild( keyTemp )
	-- print( " ---------->>> reqQueryGuild " , keyTemp )
	app.session:request("pb_guild.C2S_QueryGuild", { key = keyTemp }, function(ret)
		-- dump( ret, " ---------->>> reqQueryGuild ret" )

		self._curPageGuildInfoList = {}
		for i,v in ipairs( ret.guildInfos ) do
			local guildInfoTemp = NewguildInfo.new( v )
			table.insert( self._curPageGuildInfoList, guildInfoTemp )
		end
		app:sendMsg( "NewguildPreController", "refreshGuildList", self._curPageGuildInfoList)
	end)
end

-- 申请公会
function ClassRef:reqApplyGuild( gidTemp )
	--print( " ---------->>> reqApplyGuild " , gidTemp )
	app.session:request("pb_guild.C2S_GuildApply", { gid = {gidTemp} }, function(ret)
		-- dump( ret, " ---------->>> reqApplyGuild ret" )
		if ret.ok then
			display.pushToast( L("tips_1130005") )
			if self._curPageGuildInfoList then
				for k,v in ipairs(self._curPageGuildInfoList) do
					if v:getGuildId() == gidTemp then
						v:setApplied(true)
						break
					end
				end
			end
			--只需要通知去刷新当前数据
			app:sendMsg( "NewguildPreController", "refreshGuildListData", self._curPageGuildInfoList)
		end
	end)
end

-- 一键申请公会
function ClassRef:reqQuickApplyGuild()
	if not self._curPageGuildInfoList then
		return
	end

	local gids = {}
	self._guildApplyMap = {}
	--只用插入未申请的
	for k,v in ipairs(self._curPageGuildInfoList) do
		if not v:hadApplied() and v:getGuildMaxMemberNum() > v:getGuildMemberNum() then
			table_insert(gids,v:getGuildId())
			self._guildApplyMap[v:getGuildId()] = v
		end
	end

	app.session:request("pb_guild.C2S_GuildApply", {gid = gids}, function(ret)
		if ret.ok then
			display.pushToast( L("tips_1130005") )
			--此处要根据服务器发送回来申请成功的公会id进行处理
			for k,v in ipairs(ret.gid) do
				local guildInfo = self._guildApplyMap[v]
				if guildInfo then
					guildInfo:setApplied(true)
				end
			end

			self._guildApplyMap = {}
			--只需要通知去刷新当前数据
			app:sendMsg( "NewguildPreController", "refreshGuildListData", self._curPageGuildInfoList)
		end
	end)
end

-- 创建公会
-- string name = 1;
-- string flagBaseIcon = 2; 		// 战旗基础图案
-- string flagAdditionalIcon = 3; // 战旗附加图案
-- int32 flagBaseIconColor = 4;	// 战旗基础图案颜色
-- int32 flagAdditionalIconColor = 5;// 战旗附加图案颜色
function ClassRef:reqCreateGuild( createGuildInfo )
	-- dump( createGuildInfo, " ---------->>> reqCreateGuild " )
	app.session:request("pb_guild.C2S_GuildCreate", createGuildInfo, function(ret)
		-- dump( ret, " ---------->>> reqCreateGuild ret" )
		if ret.ok then
			self:setMyGuildInfo( ret.guildInfo )
			self:setMyGuildMemberInfo( ret.myMemberInfo )

			display.pushToast( L("tips_1130004") )
			app:sendMsg( "NewguildPreController", "closeCreateView")
			app:sendMsg( "NewguildPreController", "closeView")
			app:sendMsg( "NewguildController", "openView") -- 打开公会主页

			EM:notify("OnGuildCreated", self:getGuildName())
			self:onGuildNewApplicant(false)
		else
			display.pushToast( L("guild_creat_failed") )
		end
	end)
end

-- 拉取公会申请列表
function ClassRef:reqGuildApplyList()
	-- print( " ---------->>> reqGuildApplyList " )
	app.session:request("pb_guild.C2S_GuildApplyList", {}, function(ret)
		-- dump( ret, " ---------->>> reqGuildApplyList ret" )

		local appliedList = {}
		for i,v in ipairs( ret.guildApplys ) do
			local applicantData = guildApplicantVo.new( v )
			table.insert( appliedList, applicantData )
		end
		self:onGuildNewApplicant(#appliedList > 0)
		app:sendMsg( "NewguildController", "refreshGuildApplicantList", appliedList)
	end)
end

-- 会长处理申请者
function ClassRef:reqReplyGuildApply( uidList, approve )
	--dump( uidList, " ---------->>> reqReplyGuildApply " .. tostring( approve ) )
	app.session:request("pb_guild.C2S_GuildHandleApply", { uids = uidList, bApprove = approve }, function(ret)
		--dump( ret, " ---------->>> reqReplyGuildApply ret" )
		if ret.ok then
			self:reqGuildApplyList() -- 处理成功，重新拉取列表
		end
	end,{block = true},function()
		self:reqGuildApplyList()
	end)
end

-- 拉取公会成员列表
function ClassRef:reqGuildMemberList( gidTemp, cb )
	--print( " ---------->>> reqGuildMemberList " , gidTemp )
	app.session:request("pb_guild.C2S_GuildMemberList", { gid = gidTemp }, function(ret)
		-- dump( ret, " ---------->>> reqGuildMemberList ret" )

		self._myGuildMemberList = {}
		for k,v in pairs( ret.guildMembers ) do
			local guildMemberTemp = guildMemberVo.new( v )
			self._myGuildMemberList[ #self._myGuildMemberList + 1 ] = guildMemberTemp
		end
		self:_sortMemberList()
		app:sendMsg( "NewguildController", "refreshGuildMemberList")

		if cb then
			executeFunc(cb, self._myGuildMemberList)
		end
	end)
end

-- 扩充公会人数上限
function ClassRef:reqGuildUpperMemberLimit()
	-- print( " ---------->>> reqGuildUpperMemberLimit " )
	app.session:request("pb_guild.C2S_GuildUpperMemberLimit", {}, function(ret)
		-- dump( ret, " ---------->>> reqGuildUpperMemberLimit ret" )

		if ret.ok then
			display.pushToast( L("guild_expand_success") )
		end
	end)
end

-- 发布公会公告
function ClassRef:reqGuildNotice( titleTemp, contentTemp )
	-- print( " ---------->>> reqGuildNotice " , titleTemp , contentTemp )
	app.session:request("pb_guild.C2S_GuildNotice", { title = titleTemp, content = contentTemp }, function(ret)
		-- dump( ret, " ---------->>> reqGuildNotice ret" )

		if ret.ok then
			display.pushToast( L("guild_notice_update") )
		end
	end)
end

-- 修改公告描述
function ClassRef:reqGuildNoticeDesc( descTemp )
	-- print( " ---------->>> reqGuildNoticeDesc " , descTemp )
	app.session:request("pb_guild.C2S_GuildDescription", { desc = descTemp }, function(ret)
		-- dump( ret, " ---------->>> reqGuildNoticeDesc ret" )

		if ret.ok then
			display.pushToast( L("guild_des_update") )
			self:reqGuildRecruit()
			--EM:notify("SendGuildRecruit", {guildId = self:getGuildId(), desc = string.format(L("guild_des_recruit"), self:getGuildName(), descTemp)})
		end
	end)
end

-- 发布公会招募信息到聊天招募频道
function ClassRef:reqGuildRecruit()
	app.session:request("pb_guild.C2S_GuildRecruit", {}, function(ret)
		if ret.ok then
			--print("-------------->>>>>pb_guild.S2C_GuildRecruit")
		end
	end)
end

-- 任命职位
-- int32 uid = 1;      // 目标玩家id
-- int32 position = 2; // 职位(1；会长 2：精英 3：普通)
function ClassRef:reqAppointment( uidTemp, pos )
	if pos == 1 then
		--判断转让CD
		if not self._myGuildInfo:canChangeLead() then
			--弹出提示
			local cdTime = GD:getSystemPar( "guildPosition1CD",24 )
			display.pushToast(string.format(L("guild_Position1CD"),cdTime))
			return
		end
	end

	-- print( " ---------->>> reqAppointment " , uidTemp , pos )
	app.session:request("pb_guild.C2S_GuildAppoint", { uid = uidTemp, position = pos }, function(ret)
		-- dump( ret, " ---------->>> reqAppointment ret" )

		if ret.ok then
			display.pushToast( L("guild_appoint") )
		end
	end)
end

-- 设置自动审批 0：需要审批 1：自动通过
-- 现在似乎没有地方去设置审批
function ClassRef:reqChangeApplyMode( applyModeTemp,lvLimit,combatPowerLimit )
	--print(applyModeTemp,lvLimit,combatPowerLimit)
	app.session:request("pb_guild.C2S_GuildChangeApplyMode", { applyMode = applyModeTemp,lvLimit = lvLimit,combatPowerLimit = combatPowerLimit })
end

-- 踢出公会成员
function ClassRef:reqKickMember( uidTemp )
	-- print( " ---------->>> reqKickMember " , uidTemp )
	app.session:request("pb_guild.C2S_GuildKick", { uid = uidTemp }, function(ret)
		-- dump( ret, " ---------->>> reqKickMember ret" )

		if ret.ok then
			display.pushToast( L("guild_kick") )
		end
	end)
end

-- 公会捐献
function ClassRef:reqDonateGuild( kindTemp )
	-- print( " ---------->>> reqDonateGuild " , kindTemp )
	app.session:request("pb_guild.C2S_GuildDonate", { kind = kindTemp }, function(ret)
		-- dump( ret, " ---------->>> reqDonateGuild ret" )

		if ret.ok then
			display.pushToast( L("guild_donate") )
			app:sendMsg( "NewguildController", "refreshDonateView")
		end
	end)
end

-- 解散公会
function ClassRef:reqDismissGuild()
	if not self:isGuildLeader() then -- 我不是会长
		display.pushToast( L("lua_code_text_489") )
		return
	end
	-- print( " ---------->>> reqDismissGuild " )
	app.session:request("pb_guild.C2S_GuildDismiss", {}, function(ret)
		-- dump( ret, " ---------->>> reqDismissGuild ret" )

		if ret.ok then
			display.pushToast( L("guild_dismiss") )
			self:clearMyGuildInfo()
		end
	end)
end

-- 退出公会
function ClassRef:reqQuitGuild()
	-- print( " ---------->>> reqQuitGuild " )
	app.session:request("pb_guild.C2S_GuildQuit", {}, function(ret)
		-- dump( ret, " ---------->>> reqQuitGuild ret" )

		if ret.ok then
			display.pushToast( L("guild_quit") )
			self:clearMyGuildInfo()
		end
	end)
end

-- 邀请进入公会
function ClassRef:reqJoinGuild( targetIdTemp )
	-- print( " ---------->>> reqJoinGuild " , targetIdTemp )
	app.session:request("pb_guild.C2S_GuildInvite", { targetId = targetIdTemp }, function(ret)
		-- dump( ret, " ---------->>> reqJoinGuild ret" )
		-- bool ok = 1;
	end)
end



-- 公会挑战信息列表
function ClassRef:reqChallengeList()
	-- print( " ---------->>> reqChallengeList " )
	app.session:request("pb_guild.C2S_GuildChallengeList", {}, function(ret)
		-- dump( ret, " ---------->>> reqChallengeList ret" )
		-- 此协议已经在init中监听了
		--if ret.infos then
			--self:onGuildChallengeInfoUpdate( ret.infos )
		--end
	end)
end

-- 公会挑战奖励领取
function ClassRef:reqGetChallengeReward( challengeIdTemp )
	-- print( " ---------->>> reqGetChallengeReward " , challengeIdTemp )
	app.session:request("pb_guild.C2S_GuildChallengeGetReward", { challengeId = challengeIdTemp }, function(ret)
		-- dump( ret, " ---------->>> reqGetChallengeReward ret" )

		if ret.ok then
			-- display.pushToast( L("guild_reward") )

			local items = {0,0,0,0,0}
			for i,v in ipairs(ret.luckItems) do
				items[i] = BoxItemVo.new(v)
			end
			items = table.randomCnt(items)
			app:sendMsg("BoxController", "onOpenBox", items)

			self:reqChallengeList() -- 领取成功，重新拉取挑战信息
		end
	end)
end

--激活公会天赋技能
function ClassRef:reqActiveGuildTalent(talentId)
	app.session:request("pb_guild.C2S_ActiveSkill",{id = talentId}, function(ret)
		--if ret.ok then
			--dump( ret, " ---------->>> reqActiveGuildTalent ret" )
		--end
	end,{block = true})
end

--设置公会天赋需要的贡献等级
function ClassRef:reqSetGuildTalentDonateLv(talentId,lv)
	app.session:request("pb_guild.C2S_SetSkillDonateLv",{id = talentId,donateLv = lv}, function(ret)
		--if ret.ok then
			--dump( ret, " ---------->>> reqSetGuildTalentDonateLv ret" )
		--end
	end,{block = true})
end

--领地信息更新
function ClassRef:onGuildUpdateTerritoryInfo(ret)
	if self._myGuildInfo then
		self._myGuildInfo:updateTerritoryData(ret)
		EM:notify("onMyGuildInfoUpdate", self._myGuildInfo)
	else
		dump("======when receive territoryinfo the myguildInfo is null")
	end
end

--授予成员称号
function ClassRef:conferMemberSubTitle(uid,titleId)
	app.session:request("pb_guild.C2S_ConferMemberSubTitle",{uid = uid,titleId = titleId}, function(ret)
		if ret.ok then
			local member = self:getGuildMemberByUid(ret.uid)
			if member then
				--member:setTitleId(ret.titleId)
				app:sendMsg( "NewguildController", "refreshElevateView", {true,ret.titleId} )
			else
				dump("conferMemberSubTitle the member uid is not exist "..ret.uid)
			end
		end
	end)
end

--取消成员称号
function ClassRef:cancelMemberSubTitle(uid)
	app.session:request("pb_guild.C2S_CancleMemberSubTitle",{uid = uid}, function(ret)
		if ret.ok then
			local member = self:getGuildMemberByUid(ret.uid)
			if member then
				--member:setTitleId(0)
				app:sendMsg( "NewguildController", "refreshElevateView", {false} )
			else
				dump("cancleMemberSubTitle the member uid is not exist "..ret.uid)
			end
		end
	end)
end

--会长达到什么爵位
function ClassRef:addDynastyPromoteTips(titleId)
	local params = {
		remindId = Constant.FUNC_TYPE_DYNASTY_PROMOTE,
		dataTemp = {titleId = titleId}
	}
	local desktopController = UIHandler:getDesktopController()
	if desktopController then
		desktopController:insertFourthTips( params )
	end
end

--光辉历史
function ClassRef:addDynastyHistoryTips(data)
	local params = {
		remindId = Constant.FUNC_TYPE_DYNASTY_HISTORY,
		dataTemp = data
	}
	local desktopController = UIHandler:getDesktopController()
	if desktopController then
		desktopController:insertFourthTips( params )
	end
end

function ClassRef:isGuildTalentActive(id)
	if self._guildTalents then
		local talent = self._guildTalents[id]
		if talent then
			return talent:isActive()
		end
	end
	return false
end

-- 好运钥匙锦上添花 是否激活
function ClassRef:isGuildCharmActive()
	return self:isGuildTalentActive(10)
end

return ClassRef
